package com.ll.module_translate

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.widget.ImageButton
import android.widget.ImageView
import androidx.databinding.BindingAdapter
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.fenghuajueli.libbasecoreui.BaseApplication
import com.ll.module_translate.entity.TransResult
import com.ll.module_translate.room.TransDb
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

/**
 * @Author: ll
 * @CreateTime: 2021/10/29 09:40
 */

const val translateAppId = "20200205000380465"

const val translateSecurityKey = "E60Brnhe33kyIbCOsvmp"

const val translateUrl = "https://fanyi-api.baidu.com/api/trans/"

@BindingAdapter("copyText")
fun copyText(v: ImageButton, text: String) {
    v.setOnClickListener {
        (BaseApplication.getApplication()
            .getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager)
            .setPrimaryClip(ClipData.newPlainText("Label", text))
        ToastUtils.showLong("已复制")
    }
}

@BindingAdapter("islike")
fun isLike(v: ImageView, entity: TransResult) {
    loadImg(v, entity)

    v.setOnClickListener {
        entity.apply {
            like = !like
            update()
            loadImg(v, entity)
        }
    }
}

fun loadImg(v: ImageView, entity: TransResult) {
    Glide.with(v.context)
        .load(
            if (entity.like)
                R.drawable.ic_icon_collection_sel
            else
                R.drawable.ic_icon_collection_nor
        )
        .into(v)
}


val ioExecutor: ExecutorService = Executors.newSingleThreadExecutor()

val db = TransDb.instance.dao()

fun ioThread(block: () -> Unit) {
    ioExecutor.execute {
        block.invoke()
    }
}

fun TransResult.insert() {
    ioThread {
        db.insert(this)
    }
}

fun TransResult.update() {
    ioThread {
        like = !like
        db.update(this)
        ToastUtils.showLong(if (like) "收藏成功 " else "取消收藏")
    }
}